package com.hzc.springchan.service.impl.business;

import com.hzc.springchan.bean.entity.UserEntity;
import com.hzc.springchan.bean.request.Request;
import com.hzc.springchan.bean.response.MapDataResponse;
import com.hzc.springchan.constant.System;
import com.hzc.springchan.enums.LogOperation;
import com.hzc.springchan.enums.PrivError;
import com.hzc.springchan.enums.PubError;
import com.hzc.springchan.mapper.UserMapper;
import com.hzc.springchan.service.IBusinessService;
import com.hzc.springchan.service.IOperationLogService;
import com.hzc.springchan.service.ITokenService;
import com.hzc.springchan.util.LogUtils;
import com.hzc.springchan.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 登录业务处理类
 * @Author: chen990627
 * @Date: 2022/11/05
 **/
@Service(System.ApiBusinessName.USER_LOGIN)
public class UserLoginBusiness implements IBusinessService<Request, MapDataResponse> {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IOperationLogService operationLogService;

    @Override
    public void doBusiness(Request request, MapDataResponse response) {

        //判断用户是否存在
        String userName = (String) request.get("userName");
        String passWord = (String) request.get("passWord");

        Map<String, Object> paramMap = new HashMap<>(8);
        paramMap.put("userName", userName);
        paramMap.put("userStatus", 0);

        List<UserEntity> userEntityList = userMapper.findByOption(paramMap);
        if (CollectionUtils.isEmpty(userEntityList)) {
            LogUtils.info(this, "用户名不存在: {}", userName);
            response.setFailure(PubError.LOGIN_FAILED, PrivError.LOGIN_USERNAME_ERROR);
            return;
        }

        try {
            MD5Utils md5Utils = new MD5Utils();
            UserEntity userEntity = userEntityList.get(0);
            if (!md5Utils.checkPassWord(passWord, userEntity.getPassWord())) {
                LogUtils.info(this, "用户名为{}密码错误{}", userName, passWord);
                response.setFailure(PubError.LOGIN_FAILED, PrivError.LOGIN_PASSWORD_ERROR);
                return;
            }

            //token放入: userid
            Map<String, String> tokenMap = new HashMap<>(8);
            tokenMap.put("userId", userEntity.getId().toString());
            String token = tokenService.generate(tokenMap, "userId");
            response.getData().put(System.RequestParam.TOKEN, token);
            response.getData().put("nickName", userEntity.getNickName());

            IOperationLogService.OperationRequest operationRequest = new IOperationLogService.OperationRequest();
            operationRequest.setUserId(userEntity.getId());
            operationRequest.setOperation(LogOperation.USER_LOGIN);
            Map<String, Object> operationMap = new HashMap<>(8);
            operationMap.put("userName", userEntity.getUserEmail());

            Date date = new Date();
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String curDate = dateFormat.format(date);
            operationMap.put("createTime", curDate);
            operationRequest.setParamMap(operationMap);
            operationLogService.logOperation(operationRequest);

        }catch (NoSuchAlgorithmException e){
            LogUtils.info(this, "No such algorithm exception!");
        }catch (UnsupportedEncodingException e){
            LogUtils.info(this,"Unsupported encoding exception!");
        }
    }
}
